#include "strategy.h"

Strategy::Strategy() {}

void Strategy::init(double initialBalance)
{
    m_balance = initialBalance;
    m_initialBalance = initialBalance;

    m_trades.clear();
}

//用于更改资金费率
void Strategy::setFee(double fee)
{
    m_fee=fee;
}


//此处未添加资金费率
void Strategy::buy(const CandleData &candle, double amount)
{
    if (amount <= 0 || m_balance <= 0) return;

    m_lastPrice = candle.close;
    double totalCost = amount * candle.close;
    if (totalCost > m_balance) {
        amount = m_balance / candle.close;
        totalCost = m_balance;
    }

    m_balance -= totalCost;
    m_holdings += amount;

    TradeRecord trade;
    trade.type = TradeRecord::BUY;
    trade.timestamp = candle.timestamp;
    trade.price = candle.close;
    trade.amount = amount;
    trade.total = totalCost;
    trade.balance = getFinalBalance();
    trade.profit = trade.balance - m_initialBalance;

    m_trades.append(trade);
}



void Strategy::sell(const CandleData &candle, double amount)
{
    if (m_holdings <= 0) return;

    m_lastPrice = candle.close;
    double sellAmount = (amount <= 0) ? m_holdings : qMin(amount, m_holdings);
    double totalRevenue = sellAmount * candle.close;

    m_holdings -= sellAmount;
    m_balance += totalRevenue;

    TradeRecord trade;
    trade.type = TradeRecord::SELL;
    trade.timestamp = candle.timestamp;
    trade.price = candle.close;
    trade.amount = sellAmount;
    trade.total = totalRevenue;
    trade.balance = getFinalBalance();
    trade.profit = trade.balance - m_initialBalance;

    m_trades.append(trade);
}

